package activity_mapper

import (
	"encoding/json"
	"strings"

	"github.com/project-flogo/core/activity"
)

func init() {
	_ = activity.Register(&Activity{}, New)
}

var activityMd = activity.ToMetadata(&Settings{}, &Input{}, &Output{})

func New(ctx activity.InitContext) (activity.Activity, error) {

	// s := &Settings{}
	// err := metadata.MapToStruct(ctx.Settings(), s, true)
	// if err != nil {
	// 	return nil, err
	// }

	act := &Activity{}

	// ctx.Logger().Debugf("mappings: %+v", s.Mappings)

	// act.mapper, err = ctx.MapperFactory().NewMapper(s.Mappings)
	// if err != nil {
	// 	return nil, err
	// }

	return act, nil
}

// Activity is an Activity that is used to reply/return via the trigger
// inputs : {method,uri,params}
// outputs: {result}
type Activity struct {
	// mapper mapper.Mapper
	// current T6006
}

// Metadata returns the activity's metadata
func (a *Activity) Metadata() *activity.Metadata {
	return activityMd
}

// Eval implements api.Activity.Eval - Invokes a REST Operation
func (a *Activity) Eval(ctx activity.Context) (done bool, err error) {
	input := Input{}
	err = ctx.GetInputObject(&input)
	if err != nil {
		return true, err
	}
	b, err := json.Marshal(input.Data)
	if err != nil {
		return true, err
	}
	s := T6006{}
	err = json.Unmarshal(b, &s)
	if err != nil {
		return true, err
	}
	mapGPS := map[string]interface{}{}
	mapJSON := map[string]interface{}{}
	for k, v := range input.Data {
		if strings.HasPrefix(k, "gps_") {
			mapGPS[k[4:]] = v
		} else if strings.HasPrefix(k, "json_") {
			mapJSON[k[5:]] = v
		}
	}
	b, err = json.Marshal(mapGPS)
	if err != nil {
		return true, err
	}
	gps := T6006GPS{}
	err = json.Unmarshal(b, &gps)
	if err != nil {
		return true, err
	}
	s.GPS = gps
	s.JSON = mapJSON

	output := Output{}
	output.Data = s
	err = ctx.SetOutputObject(&output)

	return true, err
}
